#include "fun.h"

struct m_list        *root_m_list=NULL;
static struct m_list *actual_m_list=NULL;
static int            id=1;


/*this function insert new element to linked list of frames */
struct m_list*
ins_m (struct ether_header  *eth_fr){

  struct m_list *tmp;
  
  if(!(tmp=(struct m_list *)malloc(sizeof(struct m_list)))){
	printf("Cannot Malloc Memory for m_list structure\n");
	exit(1);
  }
  /*If this element is first so I need to create special root node*/
  if(root_m_list==NULL){
	root_m_list=tmp;
	actual_m_list=tmp;
	
	tmp->n_e=NULL;/*Next element null*/

	/*I copy dest a source mac address to my struct*/
	bcopy(eth_fr->ether_dhost,tmp->ether_dhost,6);
	bcopy(eth_fr->ether_shost,tmp->ether_shost,6);

	tmp->id=id++;
  }
  else{
	if(!s_m_list_addr(eth_fr->ether_dhost,eth_fr->ether_shost)){
	  actual_m_list->n_e=tmp; /*insert new element into the list */
	  
	  tmp->n_e=NULL;/*Next element null*/
	  
	  /*I copy dest a source mac address to my struct*/
	  bcopy(eth_fr->ether_dhost,tmp->ether_dhost,6);
	  bcopy(eth_fr->ether_shost,tmp->ether_shost,6);
	  
	  tmp->id=id++;
	  
	  actual_m_list=tmp; /*set new actual_list to actual end of list */
	  
	}
	else
	  return NULL;
	return tmp;
  }
  return NULL;
}

/*this function search linked list of frames for given ID a returns pointer to this structure */
struct m_list*
s_m_list_id (int s_id){
  
  struct m_list *tmp;

  if(s_id==-1)
	return NULL;
  
  tmp=root_m_list;
  
  while(tmp!=NULL){
	if(tmp->id==s_id)
	  return tmp;
	else
	  tmp=tmp->n_e;
	/*	free(tmp);
		tmp=tmp1;*/
  }
  return NULL;
}

struct m_list*
s_m_list_addr ( u_int8_t *mac1,
				u_int8_t *mac2){

  struct m_list *tmp;

  tmp=root_m_list;

  while(tmp!=NULL){
	if((!bcmp(tmp->ether_dhost,mac1,6)&&
		!bcmp(tmp->ether_shost,mac2,6))||
	   (!bcmp(tmp->ether_dhost,mac2,6)&&
		!bcmp(tmp->ether_shost,mac1,6)))
	  return tmp;
	tmp=tmp->n_e;
  }
  return NULL;
}
  
